# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re
import csv
from utils.HttpUtils import HttpUtils


requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告

"""
(.*?): (.*)
"$1":"$2",
"""


class Test_Get():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        # requests.utils.dict_from_cookiejar(html.cookies)  # 获取cookies转dict
        # res.cookies.get_dict()  # 获取cookies
        self.cookie = cookiejar.CookieJar()
        # ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        # ua = UserAgent(verify_ssl=False)  #
        self.headers = {
            # 'User-Agent': ua.random,
            'X-Appgo-Token':'',
            'X-Ivanka-Token':'',
            'X-Login-App': 'xgb',
            'X-JSON-Naming-Strategy': 'LowerCaseWithUnderscores',
            'X-Appgo-Platform': 'device=android;channel=yingyongbao',
            'X-Device-Id': 'd4c77eae83aaaba850c644fcdd4223c6',
            'X-Device-Imei': '863064352311577',
            'X-Ivanka-Platform': 'baoer-platform',
            'X-Client-Type': 'Android',
            'X-Ivanka-App': 'baoer|Android|4.9.1|5.1.1|yingyongbao|com.wallstreetcn.meepo',
            'X-Taotie-Device-Id': 'd4c77eae83aaaba850c644fcdd4223c6',
            'X-Track-Info': '{"appId":"com.wallstreetcn.meepo.android","channel":"yingyongbao","osName":"android","osVersion":"5.1.1","deviceModel":"TAS-AN00","deviceBrand":"HUAWEI","appName":"baoer","appVersion":"4.9.1","locale":"zh_CN","resolution":"900x1600","timezoneOffset":8,"deviceId":"d4c77eae83aaaba850c644fcdd4223c6","connectionType":"WIFI","orientation":"LANDSCAPE","imei":"863064352311577","carrier":"China Mobile"}',
            'Host': 'flash-api.xuangubao.cn',
            'Connection': 'Keep-Alive',
            'Accept-Encoding': 'gzip',
            'User-Agent': 'okhttp/3.13.1'
        }

    # 获取涨幅榜股票代码
    def get_contents(self, cursor):

        url = f"https://flash-api.xuangubao.cn/api/stock/rank/v2?type=change_percent&limit=6000&direction=1"

        html = HttpUtils.do_request("GET", url, self.headers, "")

        data_json = json.loads(html.text)

        source_list = data_json['data']['array']
        source_count = len(source_list)

        for index, value in enumerate(source_list):
            code = value
            print(f"========共计【{source_count}】=====当前【{index}】====代码【{code}】==========")

            name, surge_reason = self.get_code_name(code)  # 涨幅理由
            hot_txt = self.get_hot(code)  # 获取个股热点

            newCode = ""

            newCode = line[0].replace(".SS", "").replace(".SZ", "")
            if newCode[0] == "6":
                newCode = "SH" + newCode
            else:
                newCode = "SZ" + newCode

            with open("选股宝_个股热点22.csv", "a+", encoding="utf-8-sig", newline="") as f:
                csv_writer = csv.writer(f)
                csv_writer.writerow([code, newCode, name, hot_txt, surge_reason])


    # 涨幅理由
    def get_code_name(self, code):
        url = f"https://flash-api.xuangubao.cn/api/stage2/stock_info?symbols=300199.SZ,600507.SS"
        url = f"https://flash-api.xuangubao.cn/api/stage2/stock_info?symbols={code}"

        html = HttpUtils.do_request("GET", url, self.headers, "")

        data_json = json.loads(html.text)

        name = data_json['data'][code].get('stock_chi_name')  # 股票名称
        surge_reason = data_json['data'][code].get('surge_reason')  # 涨幅理由

        print(f"=======股票名称【{name}】====涨幅理由【{surge_reason}】======")

        return name, surge_reason

    # 获取个股热点
    def get_hot(self, code):
        url = f"https://flash-api.xuangubao.cn/api/stock_spotlight?symbol={code}"

        html = HttpUtils.do_request("GET", url, self.headers, "")

        data_json = json.loads(html.text)
        txt = data_json.get('data').get('text')

        print(f"=======热点：{txt}==========")

        return txt


if __name__ == '__main__':

    test_get = Test_Get()
    #
    # for i in range(1, 2):
    #     print(f"============第【{i}】页=============")
    #     a = test_get.get_contents(i)
    #     if a == 0:
    #         break
    with open("选股宝_个股热点.csv", "r", encoding="utf-8-sig", newline="") as f:
        reader = csv.reader(f)
        for line in reader:
            name, tmp = test_get.get_code_name(line[0])
            with open("选股宝_个股热点22.csv", "a+", encoding="utf-8-sig", newline="") as f1:
                csv_writer = csv.writer(f1)
                csv_writer.writerow([line[0], line[1], name, line[2]])